<?php
defined( '_JEXEC' ) or die( 'Restricted Access' );
/**
 * Helper
 *
 * @author      Alex Stolz
 * @package     Joomla
 * @subpackage  GoodRelations Module
 * @copyright   Copyright (C) 2012 Alex Stolz, Bundeswehr University Munich - All rights reserved.
 * @license     LGPL
 */

if(!defined("DS"))
    define("DS", DIRECTORY_SEPARATOR);
    
define("BASE_URI", JURI::base());
define("RDFA_DIR", dirname(__FILE__).DS.'rdfa'.DS);
$shop_uri = JRoute::_(BASE_URI."index.php?option=com_virtuemart");
define("SHOP_URI", $shop_uri );

require_once(dirname(__FILE__).DS.'rdfa'.DS.'h2o'.DS.'h2o.php');


function createRDFaSnippet($type="product", $data=null) {
    switch($type) {
        case "product":
            $product_data = $data;
            include(RDFA_DIR.'product.php');
            break;
        case "review":
            $review_data = $data;
            include(RDFA_DIR.'review.php');
            break;
        case "company":
            $company_data = $data;
            include(RDFA_DIR.'company.php');
            break;
        case "vendor":
            $store_data = $data;
            include(RDFA_DIR.'store.php');
            break;
        case "manufacturers":
            $manufacturer_data = $data;
            include(RDFA_DIR.'manufacturers.php');
            break;
        case "categories":
            $categories = $data;
            include(RDFA_DIR.'categories.php');
            break;
    }
}

// strip any occurrence of possible tags
function strip_tags_enhanced($string) {
	return trim(preg_replace("/\s+/", " ", preg_replace("/(<[^>]*>|\{[^\}]*\}|\[[^\]]*\])/", "", $string)));
}

// create w3c date format from any different time/date format
function w3cDate($time, $days_offset=0) {
    $time = $time+$days_offset*86400;
    if ((int) PHP_VERSION >= 5)
        return date('c', $time);
    else {
        $offset = date('O', $time);
        return date('Y-m-d\TH:i:s', $time).substr($offset, 0, 3).':'.substr($offset, -2);
    }
}

// notify semantic web search engines
function notifySWSE($params=null, $sitemap_uri=null, $submission_url="http://gr-notify.appspot.com/submit?uri=") {
    global $vmLogger;
    $email = "";//$company_data["email"];
    
    // submit a sitemap if exists
    if(file_exists($sitemap_uri)) {
        $ping_url = $submission_url.urlencode(BASE_URI.$sitemap_uri).($email==""?"":"&contact=".urlencode($email))."&agent=goodrelations-for-joomla-".$params->get('version');
    }
    else {
        $ping_url = $submission_url.urlencode(BASE_URI).($email==""?"":"&contact=".urlencode($email))."&agent=goodrelations-for-joomla-".$params->get('version');
    }
    
    $ping_ok = false;
    if(!preg_match("/:\/\/localhost/i", BASE_URI)) // avoid submitting "://localhost" patterns
    {
            $ping_ok = http_get($ping_url, $params);
    }
    
    if($ping_ok) {
        $db = &JFactory::getDBO();
        $db->setQuery("SELECT params FROM #__modules WHERE `module`='mod_goodrelations'" );
        $result = $db->loadObject();
        if($result) {
            $json_string = $result->params;
            $param_array = json_decode($json_string, true);
            $param_array["ping_submission_base_uri"] = $param_array["ping_submission_base_uri"].BASE_URI;
            
            $json_string_new = json_encode($param_array);
            $db->setQuery("UPDATE #__modules SET params='$json_string_new' WHERE module='mod_goodrelations'");
        }
    }
}

// perform HTTP GET on endpoint with given URL
function http_get($url, $params) {
    // file operations are allowed
    if (ini_get('allow_url_fopen') == '1') {
        $str = file_get_contents($url);
        if($str === false) {
            $http_status_code = "";
            for($i=0; $i<count($http_response_header); $i++)
            {
                if(strncasecmp("HTTP", $http_response_header[$i], 4)==0)
                {
                    // determine HTTP response code
                    $http_status_code = preg_replace("/^.{0,9}([0-9]{3})/i", "$1", $http_response_header[$i]);
                    break;
                }
            }
            echo "<p class=\"error\">Submission failed: ".$http_status_code."</p>";
        }
        return $str;
    }
    // file operations are disallowed, try it like curl
    else {
        $url = parse_url($url);
        $port = isset($url['port'])?$url['port']:80;

        $fp = fsockopen($url['host'], $port);

        if(!$fp) {
            echo "<p class=\"error\">Cannot retrieve $url</p>";
            return false;
        }
        else {
            // send the necessary headers to get the file
            fwrite($fp, "GET ".$url['path']."?".$url['query']." HTTP/1.0\r\n".
                "Host:". $url['host']."\r\n".
                "Accept: text/html\r\n".
                "User-Agent: GoodRelations Extension for Joomla v".$params->get('version')."\r\n".
                "Connection: close\r\n\r\n");

            // retrieve response from server
            $buffer = "";
            $status_code_found = false;
            $is_error = false;
            while($line = fread($fp, 4096))
            {
                $buffer .= $line;
                if(!$status_code_found && ($pos=strpos($line, "HTTP"))>=0) {
                    // extract HTTP response code
                    $response = explode("\n", substr($line, $pos));
                    $http_status_code = preg_replace("/^.{0,9}([0-9]{3})/i", "$1", $response[0]);
                    $is_error = !preg_match("/(200|406)/i", $http_status_code); // accepted status codes not resulting in error are 200 and 406
                    $status_code_found = true;
                }
            }
            fclose($fp);
                        
            if($is_error) {
                echo "<p class=\"error\">Submission failed: ".$http_status_code."</p>";
                return false;
            }
            $pos = strpos($buffer,"\r\n\r\n");
            return substr($buffer,$pos);
        }
    }
}

// fetch all parameter names that are instances of an element (like eligibleRegions) in goodrelations
function getAllParametersForElement($search, $params) {
	$db = &JFactory::getDBO();
	$db->setQuery("SELECT params FROM #__modules WHERE module='mod_goodrelations'");
	if($result = $db->loadObject()) {
	    $json_string = $result->params;
		$param_array = json_decode($json_string, true);
		foreach($param_array as $param_name=>$param_value) {
			if(preg_match("/$search/", $param_name)) {
				$param_key = preg_replace("/(_|$search)/", '', $param_name);
				if($param_value == '0') // skip radio buttons set to zero ('No')
					continue;
				else if($param_value == '1') { // one of the radio buttons ('Yes')
					if(($param_value = $params->get($param_key."_duration")) != NULL)
						$param[$param_key] = $param_value; // assign duration of warranty in months
					else
						$param[$param_key] = true; // assign true
				}
				else { // a text field param
					$param[$param_key] = $param_value;
				}
			}
		}
		return $param;
	}
}

?>